package net1;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Response {
    private int status;
    private String data;

    //客户端解析服务端返回的响应数据
    public static Response clientParse(InputStream inputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
        Response response = new Response();
        response.status = Integer.parseInt(bufferedReader.readLine());
        List<Character> list = new ArrayList<>();
        while (true) {
            char c = (char) bufferedReader.read();
            if (c == '\3') {
                break;
            }
            list.add(c);
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (char c : list) {
            stringBuilder.append(c);
        }
        response.data = stringBuilder.toString();
        return response;
    }

    //服务端返回响应给客户端
    public void serverWrite(OutputStream outputStream) throws UnsupportedEncodingException {
        PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream, "utf-8"));
        printWriter.println(status);
        printWriter.write(data + "\3");
        printWriter.flush();
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "Response{" +
                "status=" + status +
                ", data='" + data + '\'' +
                '}';
    }
}
